package com.mer.config;

import com.mer.handler.MyAccessDefineHandler;
import com.mer.handler.MyFailureHandler;
import com.mer.handler.MyLogOutSuccessHandler;
import com.mer.handler.MySuccessHandler;
import com.mer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @program: oauth-parent-137
 * @description:
 * @author: 闫克起
 * @create: 2021-10-20 09:30
 **/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private MySuccessHandler successHandler;
    @Resource
    private MyFailureHandler failureHandler;
    @Resource
    private MyLogOutSuccessHandler logOutSuccessHandler;
    @Resource
    private MyAccessDefineHandler myAccessDefineHandler;
    @Resource
    private UserService userService;

    //配置基于内存或数据库的用户信息
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .successHandler(successHandler) // 认证成功之后返回的信息
                .failureHandler(failureHandler).permitAll()
                .and().logout().logoutUrl("/logout").logoutSuccessHandler(logOutSuccessHandler).permitAll()//.logoutSuccessUrl("/login.jsp").permitAll()
                .and().exceptionHandling().accessDeniedHandler(myAccessDefineHandler) // 权限不足的时候进行使用
                .and().authorizeRequests().antMatchers("/login").permitAll()//.authenticated() // 所有的请求都需要认证
                .and().authorizeRequests().anyRequest().authenticated()
                .and().cors()// 允许跨域
                .and().csrf().disable();// 关闭csrf的保护
    }
}